import axios from 'axios'
import apiConfig from '@/api/apiConfig'
import store from '@/store'
import mdui from 'mdui'

axios.defaults.baseURL = `${apiConfig.server}`
// axios.defaults.timeout = 30000
// axios.defaults.withCredentials = true
axios.defaults.headers['Content-Type'] = 'application/json'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (store.state.token != null) {
    config.headers.Authorization = `${apiConfig.token_prefix}${store.state.token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// axios响应拦截器 拦截所有错误请求 默认弹框
axios.interceptors.response.use(
  conf => {
    if (conf.data.status >= 0) {
      return conf
    }
    return Promise.reject(conf.data)
  },
  err => {
    try {
      if (err.response.status === 401 || err.response.data === 'Unauthorized Access') {
        console.log('remove token...')
        // localStorage.removeItem('token')
        // localStorage.removeItem('username')
        localStorage.clear()
        location.reload()
      }
    } catch (error) {
      console.log(error)
      mdui.snackbar({
        message: '网络错误',
        position: 'top',
        timeout: 1000
      })
    }
    console.log('rep-reject', err)
    return err
  }
)
export default axios
